<?php
/**
 * Smarty模板视图
 * 
 * 通过Smarty模板引擎绘制模板视图。
 * 
 * @author Leo Ning <leo.ning@like18.com> 2010-11-14 12:25
 * @version 1.0
 * @since 1.0
 * @copyright 2008-2011 LIKE18 INC.
 * @package view
 */
class TemplateView extends View {
	const EXT = '.tpl';
	private $expire = 3600;
	private $__smarty;
	private $inited = false;
	public function __construct($data = array(), $tpl = '', $basedir = '') {
		parent::__construct ( $data, $tpl );
		$basedir = empty ( $basedir ) ? TEMPLATE_PATH : $basedir;
		$tpl = $basedir . $this->tpl;
		if (is_file ( $tpl )) {
			$this->__smarty = new Smarty ();
			$this->__smarty->addPluginsDir ( CORE_PLUGIN_PATH . 'smarty' );
			$this->__smarty->template_dir = $basedir; //模板目录			
			$tpl = str_replace ( DS, '/', $this->tpl );
			$tpl = explode ( '/', $tpl );
			array_pop ( $tpl );
			$sub = implode ( DS, $tpl );
			$this->__smarty->compile_dir = TMP_PATH . 'tpls_c' . DS . TEMPLATE_DIR . DS . $sub; //模板编译目录
			$this->__smarty->cache_dir = TMP_PATH . 'tpls_cache' . DS . TEMPLATE_DIR . DS . $sub; //模板缓存目录
			$this->__smarty->_dir_perms = 0775;
			if (DEBUG) {
				$this->__smarty->force_compile = true;
			}
			$this->__smarty = apply_filter ( 'init_smarty_engine', $this->__smarty );
		} else {
			Response::error ( 'The view template ' . $tpl . ' is not found', 404 );
		}
	}
	/**
	 * 
	 * 检查是否缓存了，如果缓存了，则直接输出
	 * @param int $expire
	 * @param string $cacheid
	 */
	public function cache($expire = 300, $cacheid = null) {
		$cacheid = $cacheid == null ? md5 ( request_uri () ) : md5 ( $cacheid );
		$expire = intval ( $expire );
		if ($expire > 0) {
			$this->__smarty->setCaching ( Smarty::CACHING_LIFETIME_CURRENT );
			$this->__smarty->setCacheLifetime ( $expire );
		}
		if (! empty ( $cacheid )) {
			$this->__smarty->cache_id = $cacheid;
		}
		if ($this->__smarty->isCached ( $this->tpl )) {
			$content = $this->__smarty->fetch ( $this->tpl );
			echo $content . "\n<!-- cached content -->";
			Response::close ();
		}
	}
	
	/**
	 * 绘制
	 * @param Action $action
	 * @param string $module
	 * @return string
	 */
	public function render($action, $module) {
		$data = $this->data;
		foreach ( $data as $n => $v ) {
			$this->__smarty->assign ( $n, $v ); //变量
		}
		$this->__smarty->assign ( 'controller', $action ); //变量
		return $this->__smarty->fetch ( $this->tpl );
	}
	
	public function setHeader() {
		@header ( 'Content-Type: text/html' );
	}
}